package com.op.teachingliteapp.fragment.courseDiscussion.sonCourseDiscussion;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import android.app.ActionBar.LayoutParams;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.op.teachingliteapp.R;
import com.op.teachingliteapp.common.Common;
import com.op.teachingliteapp.common.api.teachinglite.SeminarsUrl;
import com.op.teachingliteapp.util.asynctask.HttpPostTask;
import com.op.teachingliteapp.util.asynctask.OnTaskProcessListener;

public class sonSeminarAdapter extends BaseAdapter {
	private final static String TAG = sonSeminarAdapter.class.getSimpleName();
	private Context mContext;
	private ArrayList<sonSeminarData> sonSeminarList;
	private PopupWindow popWindow;
	private SharedPreferences preferences;
	private String getuserId, getSeminarId;

	public sonSeminarAdapter(Context mContext, ArrayList<sonSeminarData> bigList) {
		this.mContext = mContext;
		this.sonSeminarList = bigList;
	}

	public Context getContext() {
		return mContext;
	}

	@Override
	public int getCount() {
		// TODO Auto-generated method stub
		return sonSeminarList.size();
	}

	@Override
	public sonSeminarData getItem(int position) {
		// TODO Auto-generated method stub
		return sonSeminarList.get(position);
	}

	@Override
	public long getItemId(int position) {
		// TODO Auto-generated method stub
		return position;
	}

	@Override
	public View getView(final int position, View convertView, final ViewGroup parent) {

		final DisplayImageOptions options = new DisplayImageOptions.Builder().showImageOnLoading(R.drawable.ic_stub).showImageForEmptyUri(R.drawable.ic_empty).showImageOnFail(null)
				.cacheInMemory(true).cacheOnDisk(true).considerExifParams(true).bitmapConfig(Bitmap.Config.RGB_565).build();
		LayoutInflater lif = (LayoutInflater) mContext.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
		final View poPlayOut = lif.inflate(R.layout.big_picture, null);
		final PopupWindow popWindow = new PopupWindow(poPlayOut, LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
		popWindow.setBackgroundDrawable(new BitmapDrawable());// 这个不能删
		popWindow.setFocusable(true);// true是不可以点击下面一层。fals是可以点击下面一层
		popWindow.setOutsideTouchable(true);
		popWindow.setOnDismissListener(new poponDismissListener());
		
		LinearLayout LL = null;
		if (convertView != null) {
			LL = (LinearLayout) convertView;
		} else {
			LL = (LinearLayout) LayoutInflater.from(getContext()).inflate(R.layout.item_son_seminar, null);
		}

		final sonSeminarData data = getItem(position);

		ImageView headPortrait = (ImageView) LL.findViewById(R.id.headportrait);
		TextView userName = (TextView) LL.findViewById(R.id.name);
		TextView Title = (TextView) LL.findViewById(R.id.tile);
		TextView word = (TextView) LL.findViewById(R.id.word);
		TextView time = (TextView) LL.findViewById(R.id.time);
		TextView Owner = (TextView) LL.findViewById(R.id.Owner);
		ImageView pircture = (ImageView) LL.findViewById(R.id.pircture);
		Button like = (Button) LL.findViewById(R.id.like);
		Button commit = (Button) LL.findViewById(R.id.Comment);

		Owner.setText(data.getOwner());
		/**
		 * 从网上下拉的图片添加头像里面
		 */
		ImageLoader.getInstance().displayImage(data.getHeadPortrait(), headPortrait, options);

		/**
		 * 添加楼主的图片
		 */
		if (data.getPircture() == null || data.getPircture().equals("null")) {
			pircture.setVisibility(View.GONE);
		} else {
			pircture.setVisibility(View.VISIBLE);
			ImageLoader.getInstance().displayImage(data.getPircture(), pircture, options);
		}
		// 点击图片显示大图
		pircture.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				ImageView bigPircture = (ImageView) poPlayOut.findViewById(R.id.Picture);
				ImageLoader.getInstance().displayImage(data.getPircture(), bigPircture, options);
				backgroundAlpha(0.7f);
				popWindow.showAtLocation(parent, Gravity.CENTER, 0, 0);
				
			}
		});
		
		userName.setText(data.getName());
		Title.setText(data.getTitle());
		word.setText(data.getWord());
		time.setText(data.getTime());

		preferences = mContext.getSharedPreferences("TeachingLite", Context.MODE_PRIVATE);
		getuserId = preferences.getString(Common.Prefs.USER_ID, "");
		// getSeminarId = preferences.getString(Common.Prefs.SEMINAR_ID,
		// "");//用户id
		Button delete = (Button) LL.findViewById(R.id.delete);
		Log.i(TAG, "楼主:" + getuserId);
		Log.i(TAG, "跟帖:" + data.getUserid());
		// 判断是否是自己发的贴
		if (getuserId.equals(data.getUserid())) {
			delete.setVisibility(View.VISIBLE);
			if(position==0){
				delete.setVisibility(View.GONE);
			}else{
				delete.setVisibility(View.VISIBLE);
			}
		} else {
			delete.setVisibility(View.GONE);
		}


		delete.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				AlertDialog.Builder builder = new Builder(mContext);
				builder.setMessage("确认删除帖子吗？");
				builder.setTitle("提示");
				builder.setNeutralButton("确认", new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						Log.i(TAG, "确认删除*****************************");
						deleteItem(data.getSeminarId(), data.getUserid());
						sonSeminarList.remove(position);
						notifyDataSetChanged();
					}
				});
				builder.setNegativeButton("取消", null);
				builder.create();
				builder.show();
			}
		});


		return LL;
	}

	/**
	 * 删除网上数据库帖子方法
	 */
	public void deleteItem(String SeminarId, String Userid) {
		List<NameValuePair> params = new ArrayList<NameValuePair>();

		params.add(new BasicNameValuePair("seminarId", SeminarId));
		params.add(new BasicNameValuePair("userId", Userid));
		Log.i(TAG, "SeminarId:"+SeminarId+"UserId"+Userid);
		HttpPostTask task = new HttpPostTask(mContext, SeminarsUrl.DELETE_SEMINARS_BY_SEMINAR_ID_AND_USER_ID, params);
		task.setTaskListener(new OnTaskProcessListener() {

			@Override
			public void prepare() {
				// TODO Auto-generated method stub

			}

			@Override
			public void completed(String result) {
			}
		});
		notifyDataSetChanged();
		task.execute();
	}

	/**
	 * 设置添加屏幕的背景透明度
	 * 
	 * @param bgAlpha
	 */
	public void backgroundAlpha(float bgAlpha) {
		Window getwindow = ((Activity) mContext).getWindow();
		WindowManager.LayoutParams lp = ((Activity) mContext).getWindow().getAttributes();
		lp.alpha = bgAlpha; // 0.0-1.0
		getwindow.setAttributes(lp);
	}

	/**
	 * 添加新笔记时弹出的popWin关闭的事件，主要是为了将背景透明度改回来
	 * 
	 * @author cg
	 */
	class poponDismissListener implements PopupWindow.OnDismissListener {

		@Override
		public void onDismiss() {
			backgroundAlpha(1f);
		}

	}
}
